package com.xz.simplerpc.rpc.rest;
import com.xz.simplerpc.extension.URL;
import org.apache.commons.lang3.StringUtils;
import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
import org.jboss.resteasy.spi.ResteasyDeployment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by fingal on 2018/1/8.
 */
public class RestServer {
    private static final Logger logger = LoggerFactory.getLogger(RestServer.class);

    private final NettyJaxrsServer server = new NettyJaxrsServer();

    private static final int DEFAULT_PORT = 80;

    public void start(URL url) {
        getDeployment().getMediaTypeMappings().put("json", "application/json");
        getDeployment().getMediaTypeMappings().put("xml", "text/xml");

        doStart(url);
    }

    public void deploy(Class resourceDef, Object resourceInstance, String contextPath) {
        if (StringUtils.isEmpty(contextPath)) {
            getDeployment().getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef));
        } else {
            getDeployment().getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef), contextPath);
        }
    }

    public void undeploy(Class resourceDef) {
        getDeployment().getRegistry().removeRegistrations(resourceDef);
    }

    protected ResteasyDeployment getDeployment() {
        return server.getDeployment();
    }

    protected void doStart(URL url) {
        int port = url.getPort(DEFAULT_PORT);
        server.setPort(port);
        server.setKeepAlive(true);
        server.setExecutorThreadCount(200);
        server.setIoWorkerCount(Runtime.getRuntime().availableProcessors() + 1);
        server.start();
        logger.info("server[{}] started...", port);
    }
}
